package example.hello_security.config.entrypoint;

import cn.hutool.json.JSONUtil;
import example.hello_security.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * description 重写一个认证处理机器AuthenticationEntryPoint
 * 实现此Bean可以处理当authentic失败了之后，需要执行的逻辑
 * @author zken
 * CreateDate 2024/10/27 17:37:45
 */
@Component
public class LoginUnAuthenticationEntryPoint implements AuthenticationEntryPoint {
    // 没有token进行认证会到达此处

    /**
     * description 处理函数内容，可以使用/hello进行测试
     * @author zken
     * CreateDate 2024/10/27 17:44:29
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Result<String> error = Result.error("用户未登录，或登录已经过期");
        String json = JSONUtil.toJsonStr(error);
        response.getWriter().write(json);
    }
}
